package cn.aishua.ui.main;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import cn.aishua.data.DataProvider;
import cn.aishua.data.FindDataParser;
import cn.aishua.data.FindDataParser.FindVendor;
import cn.aishua.util.Utils;

import cn.aishua.R;

public class FindResultActivity
    extends Activity
{

    //    ImageView imageNavHeader;
    ProgressBar progressBar1;
    FindDataParser mData;
    ListView listResult;
    ListResultAdapter mAdapter;

    final int MSG_FIND_DONE = 100;
    final int MSG_DOWNLOAD_IMAGE_DONE = 200;

    //----------page -----------
    View viewLoadMore;
    TextView textLoadMore;

    String testLink = "http://h.hiphotos.baidu.com/album/s%3D740%3Bq%3D90/sign=56fdb7cca044ad342abf8583e0997dc9/9f510fb30f2442a71eede884d043ad4bd113022b.jpg";

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        Log.d( "FindResultActivity", "onCreate()" );
        super.onCreate( savedInstanceState );
        setContentView( R.layout.find_result );

        DataProvider.getInstance( this ).clearTempPic();
        init();
    }

    public void back( View view )
    {
        onBackPressed();
    }

    private void init()
    {
        //		imageNavHeader = (ImageView)findViewById(R.id.imageNavHeader);
        //		imageNavHeader.setOnClickListener(new OnClickListener() {
        //			public void onClick(View v) {
        ////				finish();
        //			    Log.d( "FindResultActivity", "onBackPressed()" );
        //				onBackPressed();
        //			}
        //		});

        progressBar1 = (ProgressBar) findViewById( R.id.progressBar1 );
        progressBar1.setVisibility( View.GONE );

        listResult = (ListView) findViewById( R.id.listResult );
        listResult.setDivider( null );
        listResult.setFadingEdgeLength( 0 );
        listResult.setVisibility( View.GONE );

        viewLoadMore = getLayoutInflater().inflate( R.layout.footer_btn, null );
        textLoadMore = (TextView) viewLoadMore.findViewById( R.id.textLoadMore );
        viewLoadMore.setOnClickListener( textLoadMoreClickListener );
        listResult.addFooterView( viewLoadMore );

        find();
    }

    Handler mHandler = new Handler()
    {
        public void handleMessage( android.os.Message msg )
        {
            switch( msg.what )
            {
                case MSG_FIND_DONE:
                    progressBar1.setVisibility( View.GONE );

                    listResult.setVisibility( View.VISIBLE );
                    mAdapter = new ListResultAdapter( FindResultActivity.this );
                    listResult.setAdapter( mAdapter );
                    break;
                case MSG_DOWNLOAD_IMAGE_DONE:
                    Object[] objs = (Object[]) msg.obj;
                    ( (ImageView) objs[0] ).setImageBitmap( (Bitmap) objs[1] );
                    break;
            }
        }
    };

    Thread findThread = new Thread()
    {
        public void run()
        {
            try
            {
                //TODO
                Thread.sleep( 2000 );
                //                mData = new FindDataParser( MyKakaTestJsonData.FIND_DATA );
                //                handleListFooter( mData.refresh() );
                mHandler.obtainMessage( MSG_FIND_DONE ).sendToTarget();
            }
            catch( InterruptedException e )
            {
                e.printStackTrace();
            }
        }
    };

    private void find()
    {
        progressBar1.setVisibility( View.VISIBLE );
        findThread.start();
    }

    class ListResultAdapter
        extends BaseAdapter
    {

        Context mContext;

        public ListResultAdapter(Context context)
        {
            mContext = context;
        }

        public int getCount()
        {
            return mData.count;
        }

        public Object getItem( int position )
        {
            return position;
        }

        public long getItemId( int position )
        {
            return position;
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            l( "position " + position + ", convertView " + convertView );
            if( convertView == null )
            {
                convertView = LayoutInflater.from( mContext ).inflate( R.layout.find_result_item, null );
                convertView.setTag( R.id.textRate, convertView.findViewById( R.id.textRate ) );
                convertView.setTag( R.id.textName, convertView.findViewById( R.id.textName ) );
                convertView.setTag( R.id.imagePic, convertView.findViewById( R.id.imagePic ) );
                convertView.setTag( R.id.textAvgPrice, convertView.findViewById( R.id.textAvgPrice ) );
                convertView.setTag( R.id.textDistance, convertView.findViewById( R.id.textDistance ) );
                convertView.setTag( R.id.textTag, convertView.findViewById( R.id.textTag ) );
                convertView.setTag( R.id.textSubCat, convertView.findViewById( R.id.textSubCat ) );
                convertView.setTag( R.id.textBusinessCir, convertView.findViewById( R.id.textBusinessCir ) );
            }

            final FindVendor d = mData.data.get( position );
            ( (ImageView) convertView.getTag( R.id.imagePic ) ).setImageResource( R.drawable.default_vendor_pic );

            ( (TextView) convertView.getTag( R.id.textRate ) ).setText( (int) ( d.max_customer_rate * 100 ) + "%" );
            ( (TextView) convertView.getTag( R.id.textName ) ).setText( d.name );
            ( (TextView) convertView.getTag( R.id.textAvgPrice ) ).setText( "人均:￥" + (int) d.average_price );
            ( (TextView) convertView.getTag( R.id.textDistance ) ).setText( "距离:" + Utils.doDistance( d.distance ) );
            ( (TextView) convertView.getTag( R.id.textTag ) ).setText( d.merchant_tags.get( 0 ) );
            ( (TextView) convertView.getTag( R.id.textSubCat ) ).setText( d.sub_category.get( 0 ) );
            ( (TextView) convertView.getTag( R.id.textBusinessCir ) ).setText( d.business_circle );

            byte[] temp = null;
            if( ( temp = DataProvider.getInstance( FindResultActivity.this ).tryGetTempPic( position ) ) != null )
            {
                l( "reused for " + position );
                Bitmap tempBitmap = BitmapFactory.decodeByteArray( temp, 0, temp.length );
                ( (ImageView) convertView.getTag( R.id.imagePic ) ).setImageBitmap( tempBitmap );
            }
            else
            {
                //TODO
                downloadImage( (ImageView) convertView.getTag( R.id.imagePic ), d.file_url, position );
                //downloadImage( (ImageView) convertView.getTag( R.id.imagePic ), testLink, position );
            }

            convertView.setOnClickListener( new OnClickListener()
            {
                public void onClick( View v )
                {
                    l( "item clicked with id " + d.id );
                    //TODO
                }
            } );

            return convertView;
        }

        private void downloadImage( final ImageView v, final String urlString, final int position )
        {
            new Thread()
            {
                public void run()
                {
                    l( "download go! for " + position );
                    try
                    {
                        URL url = new URL( urlString );
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setDoInput( true );
                        conn.connect();
                        InputStream in = conn.getInputStream();

                        Bitmap tempBitmap = BitmapFactory.decodeStream( in );

                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        tempBitmap.compress( CompressFormat.JPEG, 30, out );

                        tempBitmap.recycle();
                        tempBitmap = null;

                        //Save the bitmap
                        DataProvider.getInstance( FindResultActivity.this ).insertTempPic( position, out.toByteArray() );

                        l( "saved for " + position );
                        Bitmap newBitmap = BitmapFactory.decodeByteArray( out.toByteArray(), 0,
                            out.toByteArray().length );
                        out.close();
                        Object[] objs = { v, newBitmap };
                        mHandler.obtainMessage( MSG_DOWNLOAD_IMAGE_DONE, objs ).sendToTarget();
                        newBitmap = null;
                        in.close();
                        in = null;
                        System.gc();
                    }
                    catch( Exception e )
                    {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

    }

    //    private void handleListFooter( boolean needRemove )
    //    {
    //        if( needRemove )
    //            listResult.removeFooterView( viewLoadMore );
    //    }

    OnClickListener textLoadMoreClickListener = new OnClickListener()
    {
        public void onClick( View v )
        {
            textLoadMore.setText( "正在加载中..." );
            textLoadMore.setEnabled( false );
            mHandler.post( new Runnable()
            {
                public void run()
                {
                    //                    handleListFooter( mData.refresh("") );
                    mAdapter.notifyDataSetChanged();
                    textLoadMore.setText( "加载更多" );
                    textLoadMore.setEnabled( true );
                }
            } );
        }
    };

    private void l( String s )
    {
        android.util.Log.d( "test", s );
    }

}
